package mfuny.ggongal.admin.ad;

import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import mfuny.ggongal.admin.Server;
import mfuny.ggongal.admin.advertisers.AdvertiserDao;
import mfuny.ggongal.admin.contents.ContentDao;
import mfuny.ggongal.admin.debug.Debug;
import mfuny.ggongal.admin.games.GameDao;
import mfuny.ggongal.admin.ggongday.GgongDayDao;

import org.springframework.web.servlet.ModelAndView;

import com.ibatis.sqlmap.client.SqlMapClient;

public class AdGgongService {
	public static SqlMapClient sqlMapper;
	
	ModelAndView mav;
	GameDao gameClass;
	
	List<AdvertiserDao> advList;
	List<ContentDao> conList;
	List<GameDao> gameList;
	List<AdDao> resultList;
	List<HashMap<String, Object>> mapList;
	HashMap<String, Object> map;
	
	int dcount = 1;
	
	public AdGgongService() throws Exception {
		sqlMapper = Server.getSqlMapper( );
		mav = new ModelAndView();
		advList = new ArrayList<AdvertiserDao>();
		conList = new ArrayList<ContentDao>();
		gameList = new ArrayList<GameDao>();
		gameClass = new GameDao();
		resultList = new ArrayList<AdDao>();
		mapList = new ArrayList<HashMap<String, Object>>();
		map = new HashMap<String, Object>();
	}
	
	public ModelAndView regGgong1() throws Exception {
		mav.clear( );
		mav.setViewName( "/ad/ggong/regGgong1.ga" );
		return mav;
	}
	
	@SuppressWarnings( "unchecked" )
	public ModelAndView regGgong2( String pageNum ) throws Exception {
		gameList = sqlMapper.queryForList( "games_selectAll", null );
		mav.clear( );
		mav.setViewName( "/ad/ggong/regGgong2.ga" );
		mav.addObject( "gameList", gameList );
		return mav;
	}
	
	public ModelAndView regGgong3( int game_no ) throws Exception {
		gameClass = (GameDao)sqlMapper.queryForObject( "games_selectNo", game_no );
		mav.clear( );
		mav.setViewName( "/ad/ggong/regGgong3.ga" );
		mav.addObject( "gameClass", gameClass );
		return mav;
	}
	
	public void regGgong2( AdDao adDao ) throws Exception {
		adDao.setRegdate( new Timestamp( System.currentTimeMillis( ) ) );
		adDao.setService( "ggong" );
		try {
			sqlMapper.startTransaction( );
			sqlMapper.update( "ad_insert", adDao );
			int ad_no = (Integer) sqlMapper.queryForObject( "ad_selectLastNo", null );
			String days[] = adDao.getDays( ).split( "," );
			for ( int i = 0; i < days.length; i++ ) {
				String d[] = days[i].split( "-" );
				map.clear( );
				map.put( "year", d[0] );
				map.put( "month", d[1] );
				map.put( "day", "d" + d[2] );
				map.put( "ad_no", ad_no );
				int isMonth = (Integer) sqlMapper.queryForObject( "gday_isMonth", map );
				if ( isMonth <= 0 ) {
					sqlMapper.update( "gday_insert", map );
				} else {
					sqlMapper.update( "gday_update", map );
				}
			}
			sqlMapper.commitTransaction( );
		} finally {
			sqlMapper.endTransaction( );
		}
	}
	
	public void regGgong(AdDao adDao) throws Exception {
		adDao.setRegdate( new Timestamp( System.currentTimeMillis( ) ) );
		adDao.setService( "ggong" );
		try {
			sqlMapper.startTransaction( );
			
			sqlMapper.update( "ad_insert", adDao );
			int ad_no = (Integer) sqlMapper.queryForObject( "ad_selectLastNo", null );
			String days[] = adDao.getDays( ).split( "," );
			GgongDayDao ggongClass = null;
			Class<?> c = Class.forName( "mfuny.ggongal.admin.ggongday.GgongDayDao" );
			
			for( int i = 0; i < days.length; i++ ) {
				String d[] = days[i].split( "-" );
				map.clear( );
				map.put( "year", d[0] );
				map.put( "month", d[1] );
				ggongClass = (GgongDayDao)sqlMapper.queryForObject( "gday_selectMonth", map );
				
				if ( ggongClass == null ) {
					ggongClass = new GgongDayDao();
				}
				
				String tempD = ( c.getMethod( "getD" + d[ 2 ] ).invoke( ggongClass ) != null ? (String)c.getMethod("getD" + d[ 2 ] ).invoke( ggongClass ) : null );
				
				if ( tempD == null ) {
					c.getMethod( "setD" + d[ 2 ], String.class ).invoke( ggongClass, String.valueOf( ad_no ) );
				} else {
					c.getMethod( "setD" + d[ 2 ], String.class ).invoke( ggongClass, tempD + "," + String.valueOf( ad_no ) );
				}
				
				c.getMethod( "setYear", String.class ).invoke( ggongClass, d[0] );
				c.getMethod( "setMonth", String.class ).invoke( ggongClass, d[1] );
				
				int isMonth = (Integer) sqlMapper.queryForObject( "gday_isMonth", map );
				if ( isMonth <= 0 ) {
					sqlMapper.update( "gday_insert2", ggongClass );
				} else {
					sqlMapper.update( "gday_update2", ggongClass );
				}
			}
			
			sqlMapper.commitTransaction( );
		} catch( Exception e ) {
			e.printStackTrace( );
		} finally {
			sqlMapper.endTransaction( );
		}
	}
	
	public ModelAndView getRegistedDays( String year, String month ) throws Exception {
		String registedDays = "";
		String tempAds = "";
		map.clear( );
		map.put( "year", year );
		map.put( "month", month );
		GgongDayDao gDayClass = (sqlMapper.queryForObject( "gday_selectMonth", map ) == null ? null : (GgongDayDao) sqlMapper.queryForObject( "gday_selectMonth", map ) );
		mav.clear( );
		mav.setViewName( "/ad/ggong/getRegistedDays" );
		Class<?> c = Class.forName( "mfuny.ggongal.admin.ggongday.GgongDayDao" );
		Method m = null;
		if ( gDayClass != null ) {
			for ( int i = 1; i <= 31; i++ ) {
				m = c.getMethod( "getD" + i );
				tempAds = (String) m.invoke( gDayClass );
				registedDays += ( tempAds == null ? "" : ( registedDays.equals( "" ) ? i + "|" + tempAds : "/" + i + "|" + tempAds ) );
			}
			mav.addObject( "registedDays", registedDays );
		}
		return mav;
	}
	
	@SuppressWarnings( "unchecked" )
	public ModelAndView registedListPopup( String year, String month, String day ) throws Exception {
		List<String> param = new ArrayList<String>();
		HashMap<String, String> map2 = new HashMap<String, String>();
		map2.put( "year", year );
		map2.put( "month", month );
		map2.put( "day", "d" + day );
		String ads = (String) sqlMapper.queryForObject( "gday_adNoForDay", map2 );
		String adArray[] = ads.split( "," );
		for ( int i = 0; i < adArray.length; i++ ) {
			param.add( adArray[i] );
		}
		mapList.clear( );
		mapList = sqlMapper.queryForList( "ad_selectListNo", param );
		mav.clear( );
		mav.setViewName( "/ad/ggong/registedListPopup" );
		mav.addObject( "mapList", mapList );
		mav.addObject( "year", year );
		mav.addObject( "month", month );
		mav.addObject( "day", day );
		return mav;
	}
	
	@SuppressWarnings( "unchecked" )
	public ModelAndView selectAdvPopup() throws Exception {
		advList = sqlMapper.queryForList( "adv_selectNoOut", null );
		mav.clear( );
		mav.setViewName( "/ad/ggong/selectAdvPopup" );
		mav.addObject( "advList", advList );
		return mav;
	}
	
	@SuppressWarnings( "unchecked" )
	public ModelAndView selectAdPopup( String co_id ) throws Exception {
		conList = sqlMapper.queryForList( "con_selectById", co_id );
		mav.clear( );
		mav.setViewName( "/ad/ggong/selectAdPopup" );
		mav.addObject( "conList", conList );
		mav.addObject( "listSize", conList.size( ) );
		return mav;
	}
	
	@SuppressWarnings( "unchecked" )
	public ModelAndView getGgong() throws Exception {
//		resultList = sqlMapper.queryForList( "ad_selectGgongAll", null );
		mapList.clear( );
		mapList = sqlMapper.queryForList( "ad_selectForMapByService", "ggong" );
		mav.clear( );
		mav.setViewName( "/ad/ggong/getGgong.ga" );
		mav.addObject( "mapList", mapList );
		return mav;
	}
	
	//등록된 꽁게임 상세보기.
	@SuppressWarnings("unchecked")
	public ModelAndView detailGgongGame(int ad_no) throws Exception {
		HashMap<String, Object> resultClass = (HashMap<String, Object>) sqlMapper.queryForObject("ad_selectAllOne2", ad_no);
		int score = MissionDetail.getScore_mission((String)resultClass.get("mission"));
		String offerGgong = MissionDetail.getOfferGgong_mission((String)resultClass.get("mission"));
		mav.clear();
		mav.setViewName("/ad/ggong/detailGgongGame.ga");
		mav.addObject("resultClass", resultClass);
		mav.addObject("m_score", score);
		mav.addObject("offerGgong", offerGgong);
		return mav;
	}
	
	//꽁모으기 광고 삭제하기(컨트롤).
	public ModelAndView deleteGGame(int ad_no) throws Exception {
		int result = deleteGGameWork(ad_no);
		mav.clear();
		mav.setViewName("/blank");
		mav.addObject("value", result);
		return mav;
	}
	
	//꽁모으기 광고 삭제하기(처리).
	public int deleteGGameWork(int ad_no) throws Exception {
		AdDao ad = (AdDao) sqlMapper.queryForObject("ad_selectNo", ad_no);
		String[] beforeDays = ad.getDays().split(",");
		int result = 0;
		
		try{
			sqlMapper.startTransaction();
			sqlMapper.startBatch();
			for(int i = 0; i < beforeDays.length; i++) {
				//연 + 월 ggongday 가져오기.
				String[] days = beforeDays[i].split("-");
				HashMap<String, Object> paramForDay = new HashMap<String, Object>();
				paramForDay.put("year", Integer.parseInt(days[0]));
				paramForDay.put("month", Integer.parseInt(days[1]));
				GgongDayDao gDay = (GgongDayDao) sqlMapper.queryForObject("gday_selectMonth", paramForDay);
				Method m = gDay.getClass().getMethod("getD" + Integer.parseInt(days[2]));
				Object dayObject = m.invoke(gDay);
				if( dayObject == null ) {
					continue;
				}
				
				String[] dayValues = ((String)dayObject).split(",");
				String paramValue = "";
				for(int j = 0; j < dayValues.length; j++) {
					if( dayValues[j].equals(String.valueOf(ad_no)) ) {
						continue;
					}
					paramValue += (paramValue.equals("") ? "" : ",") + dayValues[j];
				}
				paramForDay.put("day", "d" + Integer.parseInt(days[2]));
				paramForDay.put("dayvalue", !paramValue.equals("") ? paramValue : null);
				sqlMapper.update("gday_updateForDelete", paramForDay);
			}
			result = sqlMapper.executeBatch();
			if( result <= 0 ) {
				throw new Exception("day update error");
			}
			
			//광고번호 삭제.
			result = sqlMapper.update("ad_delete", ad_no);
			if( result <= 0 ) {
				throw new Exception("delete error");
			}
			
			sqlMapper.commitTransaction();
			result = 1;
			
		} catch(Exception e) {
			Debug.toDebugFile(e, "deleteGGame");
			result = -1;
			
		} finally {
			sqlMapper.endTransaction();
		}
		
		return result;
	}
}
